<template>
  <div id="fsiIndexMap-map" style="width:100%;height:658px;"></div>
</template>
<script>
import '@/assets/map/ol/ol.css';
import { getProjection } from "@/map/projMap.js";
import Map from 'ol/Map';
import View from 'ol/View';
import VectorLayer from 'ol/layer/Vector';
import {Vector as VectorSource} from 'ol/source';
import WKT from 'ol/format/WKT';
import {boundingExtent} from 'ol/extent';
import {Fill, Stroke, Style, Icon, Circle as CircleStyle,Text} from 'ol/style';
import dingweiImg from '@/assets/map/image/newImage/blueMarker.png';


export default {
  name: "FsiIndexMap",
  components: {

  },
  props:{
    fsiLegendList:{//地震影响场图例列表
      type:Array,
      required:false,
      default: []
    },
    fastSiVersion:{//地震影响场版本信息
      type:Object,
      required:false,
      default: {}
    },
    fastSeismicInfluenceList:{//地震影响场数据列表
      type:Array,
      required:false,
      default: []
    },
    centerLonLat:{//中心点
      type:Array,
      required:false,
      default: []
    },
    dzLonLat:{//地震经纬度
      type:Array,
      required:false,
      default: []
    },
    clickParams: {//地图点击选择的地震影响场烈度
      type:Object,
      required:false,
      default: {}
    },
  },
  emits:["getMap"],
  data() {
    return {
      str: "fsiIndexMap",
      map: null,
      center: [105, 34],
      zoom: 4,
      fsiLegendArray:[],//地震影响场图例数组
      fastSeismicInfluenceArray:[],//地震影响场数据列表
      fsiDataLayer:null,//地震影响场空间数据图层
      centerPointLayer:null,//地震影响场中心点图层
      dzPointLayer:null,//地震震中点图层
    }
  },
  watch: {
    fsiLegendList:{//地震影响场图例列表
      handler: function(newVal,oldVal){
        if(newVal!=oldVal){
          console.log("地震影响场图例列表");
          console.log(newVal);
          this.fsiLegendArray = newVal;
        }
      },
      immediate:true
    },
    fastSiVersion:{//地震影响场版本信息
      handler: function(newVal,oldVal){
        console.log("地震影响场版本信息");
        console.log(newVal);
      },
      immediate:true
    },
    fastSeismicInfluenceList:{//地震影响场数据列表
      handler: function(newVal,oldVal){
        console.log("地震影响场数据列表");
        this.fastSeismicInfluenceArray = newVal;
        this.showFastSeismicInfluenceList();//显示地震影响场数据列表
      },
      immediate:true
    },
    centerLonLat:{//中心点
      handler: function(newVal,oldVal){
        this.showCenterPoint(newVal);//显示地震影响场中心点
      },
      immediate:true
    },
    dzLonLat: {//地震经纬度
      handler: function(newVal,oldVal){
        this.showDzPoint(newVal);//显示地震点
      },
      immediate:true
    },
    clickParams: {//地图点击选择的地震影响场烈度
      handler: function(newVal,oldVal){

      },
      immediate:true
    },
  },
  created() {

  },
  mounted() {
    console.log("mounted");
    let that = this;
    //地图异步加载
    this.$nextTick(function(){
      console.log('地图异步加载');
      //地图异步加载
      setTimeout(() => {
        //初始化地图信息
        that.initMap();
        //显示地震点
        that.showDzPoint(that.dzLonLat);
      }, 200);
    });
  },
  beforeCreate() {//生命周期创建之前
    console.log("beforeCreate");
  },
  beforeMount() {//生命周期挂载之前
    console.log("beforeMount");
  },
  beforeUpdate() {//生命周期更新之前
    console.log("beforeUpdate");
  },
  updated() {//生命周期更新之后
    console.log("updated");
  },
  beforeDestroy() {//生命周期销毁之前
    console.log("beforeDestroy");
  },
  destroyed() {//生命周期销毁完成
    this.map = null;
    console.log("销毁地图");
  },
  activated() {//如果页面有keep-alive缓存功能激活，这个函数会触发
    console.log("activated-"+this.str);
    //自动获取地图div高度
    this.autodivheight();
    //浏览器窗口发生变化时同时变化DIV高度
    window.onresize=this.autodivheight;
  },
  deactivated() {//如果页面有keep-alive缓存功能停用，这个函数会触发
    console.log("deactivated-"+this.str);
    //取消浏览器窗口发生变化时同时变化DIV高度事件
    window.onresize = null;
  },
  methods: {
    initMap() {
      let that = this;
      let mapStr = this.str;
      let targetMap = document.getElementById(mapStr+"-map");
      if(targetMap.innerHTML!=""){
        console.log("清空targetMap");
      }
      targetMap.innerHTML = "";//清空
      //自动获取地图div高度
      this.autodivheight();
      //浏览器窗口发生变化时同时变化DIV高度
      window.onresize=this.autodivheight;
      if(this.map){//避免重复加载地图
        console.log("避免重复加载地图");
        return;
      }
      console.log("初始化地图");
      //获取投影4490坐标系
      this.projection4490 = getProjection();
      //初始化地图信息
      this.map = new Map({
        target: targetMap.id,
        /*controls: defaultControls({attributionOptions: {collapsed: false}})
            .extend([new Logo()]),*/
        view: new View({
          center: this.center,
          maxZoom: 18,
          minZoom: 4,
          zoom: this.zoom,
          constrainResolution:true,//缩放地图可移动到最近的缩放级别（整数zoom级别）
          projection: 'EPSG:4490',
          // resolutions:getResolutions()
        })
      });
      console.log("this.map");
      console.log(this.map);

      //地震影响场空间数据图层
      this.fsiDataLayer = new VectorLayer({
        source: new VectorSource({
          wrapX: false
        }),
        projection: 'EPSG:4490'
      });
      this.map.addLayer(this.fsiDataLayer);
      this.fsiDataLayer.setZIndex(1);

      //中心点
      this.centerPointLayer = new VectorLayer({
        source: new VectorSource({
          wrapX: false
        }),
        projection: 'EPSG:4490'
      });
      this.map.addLayer(this.centerPointLayer);
      this.centerPointLayer.setZIndex(2);

      //地震经纬度点
      this.dzPointLayer = new VectorLayer({
        source: new VectorSource({
          wrapX: false
        }),
        projection: 'EPSG:4490'
      });
      this.map.addLayer(this.dzPointLayer);
      this.dzPointLayer.setZIndex(2);

      //地图对象传递
      this.$emit("getMap",this.map);
    },
    autodivheight() {//自动获取div高度
      //获取浏览器窗口高度
      let winHeight = 0;
      if (window.innerHeight) {
        winHeight = window.innerHeight;
      } else if ((document.body) && (document.body.clientHeight)) {
        winHeight = document.body.clientHeight;
      }
      //通过深入Document内部对body进行检测，获取浏览器窗口高度
      if (document.documentElement && document.documentElement.clientHeight) {
        winHeight = document.documentElement.clientHeight;
      }
      //全屏时窗口高度:864px,地图div高度:754px
      let tempHeight = 864;
      let mapTempHeight = 754;
      let mapHeight = winHeight - tempHeight + mapTempHeight;
      //最小高度
      if(mapHeight<480){
        mapHeight = 480;
      }
      //设置地图高度
      document.getElementById(this.str+"-map").style.height= mapHeight +"px";
      console.log("窗口高度："+winHeight+"地图高度："+mapHeight);
      //resize事件--刷新地图,确保地图不变形
      if(this.map){
        this.map.updateSize();
        console.log("resize事件--刷新地图,确保地图不变形");
      }
    },
    getPointImgStyle(){// 点图标样式
      let style = new Style({
        image: new Icon({
          src: dingweiImg,
          // anchor: [0.5, 1]
          anchor: [0.5, 0.8]
        }),
      });
      return style;
    },
    getPointStyle(color,fillColor){// 点样式
      let style = new Style({
        image: new CircleStyle({
          radius:5,
          fill:new Fill({//填充样式
            color:fillColor
          }),
          stroke:new Stroke({//描绘
            width:1,//宽
            color:color
          }),
        }),
      });
      return style;
    },
    getPolyonStyle(color,fillColor,width){//多边形样式
      if(fillColor!=null){
        //填充样式
      }else{
        fillColor = "rgba(0,0,0,0)";
      }
      if(width!=null){
        //线宽度
      }else{
        width = 2;
      }
      let style = new Style({
        fill:new Fill({//填充样式
          color:fillColor
        }),
        stroke:new Stroke({//描绘
          width:width,//宽
          color:color
        })
      });
      return style;
    },
    getPolyonTextStyle(color,backgroundColor,text){//多边形文字样式
      if(backgroundColor==null){
        backgroundColor = "rgba(0,0,0,0)";
      }
      let style = new Style({
        fill:new Fill({//填充样式
          color:backgroundColor
        }),
        stroke:new Stroke({//描绘
          width:1,//宽
          color:color
        }),
        text: new Text({
          text: text,
          fill: new Fill({
            color: 'black'
          }),
          offsetY:20,
          font:'bold 14px 微软雅黑',
        })
      });

      return style;
    },
    getSelectPolyonStyle(){//选中要素样式
      let style = new Style({
        fill:new Fill({//填充样式
          color:"rgba(255,255,255,0.2)"
        }),
        stroke:new Stroke({//描绘
          width:2,//宽
          color:"rgba(30,144,255,1)"
        })
      });
      return style;
    },
    showBoundingExtent(coordinates){//缩放到区域位置
      console.log("缩放到区域位置");
      if (coordinates!=null && coordinates.length > 1) {
        const extent = boundingExtent(coordinates);
        //this.map.getView().fit(extent, {duration: 1000, padding: [50, 50, 50, 50]});
        this.map.getView().fit(extent, {padding: [50, 50, 50, 50]});
        //获取默认位置
        this.center = this.map.getView().getCenter();
        this.zoom = this.map.getView().getZoom();
      }
    },
    //获取烈度获取填充颜色
    getFillColorByValue(val){
      let fillColor = null;
      if(val && this.fsiLegendArray && this.fsiLegendArray.length>0){
        for(let i=0;i<this.fsiLegendArray.length;i++){
          if(this.fsiLegendArray[i].value==val){
            fillColor = this.fsiLegendArray[i].color;
            break;
          }
        }
      }

      return fillColor;
    },
    //获取烈度获取图例序号
    getLegendIndexByValue(val){
      let index = null;
      if(val && this.fsiLegendArray && this.fsiLegendArray.length>0){
        for(let i=0;i<this.fsiLegendArray.length;i++){
          if(this.fsiLegendArray[i].value==val){
            index = i;
            break;
          }
        }
      }

      return index;
    },
    showFastSeismicInfluenceList(){//显示地震影响场数据列表
      if(this.fsiDataLayer!=null){
        this.fsiDataLayer.getSource().clear();//清空
        let list = this.fastSeismicInfluenceArray;
        if(list!=null && list.length>0){
          //全部经纬度
          let allCoordinates = [];
          for(let i=0;i<list.length;i++){
            let fvId = list[i].fvId;//版本ID
            let intensity = list[i].intensity;//烈度
            //获取烈度获取图例序号
            let legendIndex = this.getLegendIndexByValue(intensity);
            if(legendIndex>=0){
              // let fillColor = this.getFillColorByValue(intensity);//获取烈度获取填充颜色
              let fillColor = this.fsiLegendArray[legendIndex].color;
              let intensityStr = this.fsiLegendArray[legendIndex].name;
              // let style = this.getPolyonStyle("rgba(255,255,255,0.7)",fillColor,0.5);
              //样式
              let style = this.getPolyonTextStyle("rgb(152,152,152)", fillColor, intensityStr);
              let geomText = list[i].geom;//空间数据
              if(geomText!=null && geomText!="" && geomText!="POLYGON EMPTY"){
                //空间数据
                let featureTmp = new WKT().readFeature(geomText);
                //设置属性
                featureTmp.setProperties({
                  type:"fsi",//类型
                  fvId:fvId,
                  intensity:intensity,//烈度
                });
                featureTmp.setStyle(style);
                //添加矢量数据
                this.fsiDataLayer.getSource().addFeature(featureTmp);
                //获取范围
                let extent = featureTmp.getGeometry().getExtent();
                if(extent.length==4){
                  //全部经纬度--左下角
                  allCoordinates.push([extent[0],extent[1]]);
                  //全部经纬度--右上角
                  allCoordinates.push([extent[2],extent[3]]);
                }
              }
            }
          }
          let that = this;
          setTimeout(function(){
            that.showBoundingExtent(allCoordinates);//缩放到区域位置
          },200);
        }
      }
    },
    showCenterPoint(lonlat) {//显示地震影响场中心点
      if (this.centerPointLayer != null) {
        this.centerPointLayer.getSource().clear();//清空
        if(lonlat!=null && lonlat.length==2){
          let geomText = "POINT("+lonlat[0]+" "+lonlat[1]+")";
          //样式
          let style = this.getPointStyle("orange", "orange");
          //空间数据
          let featureTmp = new WKT().readFeature(geomText);
          featureTmp.setStyle(style);
          //添加矢量数据
          this.centerPointLayer.getSource().addFeature(featureTmp);
          this.$emit('setEpicenterLayerBool')
        }
      }
    },
    showDzPoint(lonlat) {//显示地震点
      let that = this;
      if (this.dzPointLayer != null) {
        this.dzPointLayer.getSource().clear();//清空
        if(lonlat!=null && lonlat.length==2){
          let geomText = "POINT("+lonlat[0]+" "+lonlat[1]+")";
          //样式
          let style = this.getPointStyle("red", "red");
          //空间数据
          let featureTmp = new WKT().readFeature(geomText);
          featureTmp.setStyle(style);
          //添加矢量数据
          this.dzPointLayer.getSource().addFeature(featureTmp);
          //设置位置
          setTimeout(function(){
            that.map.getView().setCenter(lonlat);
          },200);
        }
      }
    },
  }
}

</script>

<style lang="scss" scoped>

</style>